import 'package:ai/config/Config.dart';
import 'package:ai/util/SharedPreferencesUtil.dart';
import 'package:dio/dio.dart';

class DioUtil {
  static final DioUtil _instance = DioUtil._internal();

  factory DioUtil() => _instance;
  late Dio dio;

  DioUtil._internal() {
    BaseOptions options = BaseOptions(
      baseUrl: Config.baseUrl,
      connectTimeout: const Duration(milliseconds: 5000),
      receiveTimeout: const Duration(milliseconds: 3000),
      headers: {
        "Content-Type": "application/json",
      },
    );
    dio = Dio(options);
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        print("请求前:${options.data.toString()}");
        return handler.next(options);
      },
      onResponse: (response, handler) {
        print("响应成功:${response.data}");
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        // 错误处理
        print("请求错误:${e.message}");
        return handler.next(e);
      },
    ));
  }
  Future<Response> get(String path,
      {Map<String, dynamic>? queryParameters,
      Options? options,
      CancelToken? cancelToken}) async {
    try {
      Options newOptions = options??Options();
      Map<String, dynamic> headers = newOptions.headers ?? {};
      headers.addAll({
        "token":SharedPreferencesUtil().getString("token"),
      });
      newOptions.headers = headers;

      Response response = await dio.get(path,
          queryParameters: queryParameters,
          options: options,
          cancelToken: cancelToken);
      return response;
    } catch (e) {
      rethrow;
    }
  }
  Future<Response> post(String path,
      {Map<String, dynamic>? data, Map<String, dynamic>? queryParameters,
      Options? options,
      CancelToken? cancelToken}) async {
    try {
      FormData formData = FormData.fromMap(data ?? {});
      Options newOptions = options??Options();
      Map<String, dynamic> headers = newOptions.headers ?? {};
      headers.addAll({
        "token":SharedPreferencesUtil().getString("token"),
      });
      newOptions.headers = headers;

      Response response = await dio.post(path,
          data: formData,
          queryParameters: queryParameters,
          options: newOptions,
          cancelToken: cancelToken);
      return response;
    } catch (e) {
      rethrow;
    }
  }

  void uploadFile() async {
    try {
      var filePath = 'path/to/your/file.jpg';
      var formData = {
        'file': await MultipartFile.fromFile(filePath, filename: 'upload.jpg')
      };
      var response = await DioUtil().post('/upload', data: formData);
      print(response.data);
    } catch (e) {
      print('Error: $e');
    }
  }


}
